﻿// ===============================================================================
// Copyright (c) 2007-2020 西安交通信息投资营运有限公司 版权所有
// 作者:焦元义
// ===============================================================================

using System;
using XCI.Helper;
using XCI.Sys.Model;
using XCI.Sys.Service;
using XCI.Windows;

namespace XCI.Sys.Forms
{
    public partial class FrmDicBatchEdit : BaseForm
    {
        public FrmDicBatchEdit(EditFormArgs args)
        {
            InitializeComponent();
            layoutControl.Args = args;
        }

        /// <summary>
        /// 页面加载事件
        /// </summary>
        private async void FrmDicEdit_Load(object sender, EventArgs e)
        {
            await layoutControl.BindingModelAsync();
        }

        private async void btnSave_Click(object sender, EventArgs e)
        {
            await layoutControl.SaveModelAsync();
        }

        private void BtnClose_Click(object sender, EventArgs e)
        {
            DialogOk();
        }

        /// <summary>
        /// 绑定表单
        /// </summary>
        private void LayoutControl_BindingForm(object sender, EditFormPanelBindingEventArgs e)
        {
            e.Task = async () =>
            {
                var model = await SysDicService.Instance.GetOrCreateDicAsync(e.Args);
                model.DicCategory = await SysDicService.Instance.SelectDicCategoryByCodeAsync(model.Code);
                bindingSource.DataSource = model;
                await parentDicTreeList.SetDataSource(e.Created, model.Id, model.Code);
                WinFormHelper.SetTreeRootValue(parentDicTreeList, e.ParentId);
            };
        }

        /// <summary>
        /// 保存表单
        /// </summary>
        private void LayoutControl_SaveForm(object sender, EditFormPanelSaveEventArgs e)
        {
            e.Task = async () => await SysDicService.Instance.BatchInsertDicAsync((SysDic)e.Model, editContent.Lines);
        }

        private void LayoutControl_ValidateForm(object sender, EditFormPanelValidateEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(editContent.Text.Trim()))
            {
                MessageBoxHelper.ShowWarn("请输入批量保存的内容");
                e.Result = false;
            }
        }
    }
}